using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;
using Apache.Cassandra;


namespace Cassandraemon
{

	class ObjectCassandraEntityConverter<TInput, TOutput> : CassandraEntityConverterBase<TInput, TOutput>
	{
		
		public ObjectCassandraEntityConverter (CassandraEntity<TInput> entity) : base(entity) { }
		
		
		public TOutput ToObject()
		{
			if(Object is IEnumerable)
			{
				throw new InvalidOperationException("You can't specify IEnumerable type when use ToObject.");
			}

			if(typeof(TInput).Equals(typeof(CounterColumn)) ||
			   typeof(TInput).Equals(typeof(CounterSuperColumn)) ||
			   typeof(TInput).Equals(typeof(List<CounterColumn>)) ||
			   typeof(TInput).Equals(typeof(List<CounterSuperColumn>)))
			{
				throw new InvalidOperationException("You can't use ToObject when you get CounterColumn.");
			}

			if(Entity.Data == null) return default(TOutput);
			
			List<Column> columns = null;
			
			if(Type.Equals(typeof(List<SuperColumn>)))
			{
				var superColumnList = (Entity.Data as List<SuperColumn>);
				if(superColumnList.Count == 0) return default(TOutput);
				columns = GetFlatColumnList((TInput)(object)new List<SuperColumn>{superColumnList[0]});
			}
			else
			{
				columns = GetFlatColumnList(Entity.Data);
			}
			
			if(columns == null) return default(TOutput);
			if(columns.Count == 0) return default(TOutput);
			
			return MappingUtil.MappingObject<TOutput>(columns);
		}
		
	}
}
